import Vue from 'vue'
import Vuex from 'vuex'
import {store} from "core-js/internals/reflect-metadata";

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        cartArray:[]
    },
    getters: {
        getSumPrice(state){
            let sum = 0;
            state.cartArray.forEach(a=>{
                sum+=a.count*a.price;
            })
            return sum;
        },
        getSumCount(state){
            let sum = 0;
            state.cartArray.forEach(a=>{
                sum+=a.count;
            })
            return sum;
        }
    },
    mutations: {
        setCart(state,obj){
            state.cartArray = obj;
        },
        delCart(state,pi){
            state.cartArray=state.cartArray.filter(value => {
                return value.product_id !== pi;
            })
        }
    },
    actions: {
        getCart({commit}){
            return new Promise((resolve,reject)=>{
                Vue.axios.get('api1/cartGet').then(response=>{
                    commit('setCart',response.username)
                    resolve("ok");
                }).catch(error=>{
                    console.log(error);
                    reject(error);
                })
            })
        },
        addCart(context,product){
            let jg = this.state.cartArray.some(v=>{
                return v._id === product._id;
            })
            if(jg){
                this.state.cartArray.filter(v=>{
                    if(v._id===product._id){
                        v.count++;
                    }
                })
            }else{
                /* 因为添加的对象不一致 重新发送一边axios请求获取最新的cartArray */
                context.commit('getters');
            }
        }
    },
    modules: {}
})